function h = meshplot(mesh)
  % MESHPLOT
  %
  % h = meshplot(mesh)
  %
  % Plot a mesh using an external viewer. 
  %
  % Input:
  %    File Format:
  %  
  %  Mesh is a matlab structures that contains the following matrices. 
  %  n is the number of vertices and m the number of faces.
  %  
  %  Vertex-related:
  %    V  = nx3 Position of the vertices
  %    VC = nx3 Color of vertices (0.0-1.0)
  %    VN = nx3 Normal of the vertex
  %    VT = nx2 Tex coordinate
  %  
  %  Face-related:
  %    F  = mx[3|4] Indices that define the face
  %    FC = mx3 Face colors (0.0-1.0)
  %    FN = mx3 Face normals
  %  
  %  Texture-related:
  %    TEXTURE = rgb texture as returned by the matlab function imread
  %  
  %  Illustrative (i.e. not related to the mesh in any way :)
  %  
  %    L = ax9 Define a set of lines in 3d space. 
  %  
  %      Every row describes a line following this format 
  %      (p1_x,p1_y,p1_z,p2_x,p2_y,p2_z,r,b,g) where 
  %      p1 and p2 are the extremes of the line and r,g,b are the three
  %      components of the rgb color associated with the line. The color 
  %      is defined in float format.
  %   
  %    B = ax7 Define a set of spheres in 3d space.
  %  
  %      Every row describes a sphere following this format 
  % 	 (c1_x,c1_y,c1_z,radius,r,b,g) where 
  %      c is the center, radius the radius and r,g,b is the associated color
  %      in float format.
  %  
  %    TEXTP = ax3 Defines a set of point in 3d to which labels can be attached 
  %  
  %    TEXTC = ax* array of strings to be attached to the points defined in TEXTP
  % 
  % Output:
  %  h  handle to external viewer
  %

  % get a temporary file name, by appending .mp we're losing the guarantee
  % that the file name is unique, simple to check though and almost always it
  % is so not sure if this is worth worrying about
  
  
  % sanity checks
  if (isfield(mesh,'VC') && size(mesh.VC) ~= size(mesh.V))
    error('VC must have the same size as V');
  end
  
  if (isfield(mesh,'FC') && (size(mesh.FC,1) ~= size(mesh.F,1) || size(mesh.FC,2) ~= 3))
    error('FC must have the same size as F');
  end
  
  Preview3DPath = '/usr/local/bin/';
  
  h.basename = tempname;
  h.filename = [h.basename '.mp'];
  while(exist(h.filename,'file'))
    h.basename = h.tempname;
    h.filename = [h.basename '.mp'];
  end

  % write as mp
  save(h.filename,'mesh');

  % issue system call to open external viewer
  command = [Preview3DPath 'Preview3D ' h.filename '&'];
  % fprintf([command '\n']);
  [status, result] = system(command);
  ! osascript -e "tell application \"Preview3D\" to activate";
end
